package conson.tech.manage.facade.controller.activity.mobile;

import cn.hutool.json.JSONUtil;
import conson.tech.core.constant.SecurityConstants;
import conson.tech.manage.activity.service.MessagePushService;
import conson.tech.manage.activity.service.TicketRecordService;
import conson.tech.manage.api.activity.form.TicketUseDataForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: TicketNoticeController
 * Description:
 * Author: HXL
 * Date: 2020/5/25 10:40 上午
 * Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping(SecurityConstants.NOTICEAPI+"/ticket/")
public class TicketNoticeController {

    @Autowired
    private TicketRecordService ticketRecordService;
    @Autowired
    private MessagePushService messagePushService;
    @PostMapping("use")
    public void ticketUseInfo(HttpServletRequest request, HttpServletResponse response, @RequestBody TicketUseDataForm form){
        log.info("业务系统通知票券的使用情况的入参:[{}]", JSONUtil.toJsonStr(form));
        PrintWriter out = null;
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
        } catch (IOException e) {
            log.error("获取response写入流失败:",e);
            return;
        }
        Map<String,String> map = new HashMap<>();
        try {
            int i = ticketRecordService.updateTicketRecord(form.getBusTicketId(),form.getStatus());
            if (i>0) {
                //推送
                try {

                    messagePushService.pushMessage(form.getBusTicketId());
                } catch (Exception e) {
                   log.error("票券使用 -> messagePushService.pushMessage 发送推送消息出错",e);
                }
                map.put("code", "200");
                map.put("msg", "success");
                out.write(JSONUtil.toJsonStr(map));//response的输出流
            }else {
                log.info("业务系统通知票券的使用情况修改数据库没有修改数据");
                map.put("code", "400");
                map.put("msg", "没有修改数据");
                out.write(JSONUtil.toJsonStr(map));//response的输出流
            }
        } catch (Exception e) {
            log.error("业务系统通知票券的使用情况出现异常:",e);
            map.put("code", "500");
            map.put("msg", "fail");
            out.write(JSONUtil.toJsonStr(map));//response的输出流
            return;
        }finally {
            if (out != null){
                out.close();
            }
        }

    }
}
